#include <arpa/inet.h>
#include <ifaddrs.h>
#include <iostream>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/socket.h>

int main()
{
    struct ifaddrs *ifaddr, *ifa;
    char ip[ INET6_ADDRSTRLEN ];

    // 获取所有网络接口地址
    if ( getifaddrs( &ifaddr ) == -1 )
    {
        perror( "getifaddrs" );
        return 1;
    }

    // 遍历每个接口
    for ( ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next )
    {
        if ( ifa->ifa_addr == NULL )
            continue;

        int family = ifa->ifa_addr->sa_family;

        // 处理IPv4地址
        if ( family == AF_INET )
        {
            std::string interface_name( ifa->ifa_name );
            if ( interface_name == "lo" )
                continue;
            struct sockaddr_in *sa = ( struct sockaddr_in * )ifa->ifa_addr;
            inet_ntop( AF_INET, &sa->sin_addr, ip, sizeof( ip ) );
            printf( "Interface: %s, IPv4 Address: %s\n", ifa->ifa_name, ip );
        }
        // 处理IPv6地址
        // else if ( family == AF_INET6 )
        // {
        //     struct sockaddr_in6 *sa = ( struct sockaddr_in6 * )ifa->ifa_addr;
        //     inet_ntop( AF_INET6, &sa->sin6_addr, ip, sizeof( ip ) );
        //     printf( "Interface: %s, IPv6 Address: %s\n", ifa->ifa_name, ip );
        // }
    }

    // 释放内存
    freeifaddrs( ifaddr );
    std::cout << ip << std::endl;
    return 0;
}
